<template>
  <div>
    <div :class="title == '编辑采购单' ?'editMenu' :'addMenu' ">
      <split-vertical :title="title"></split-vertical>
      <el-row class="purOrder-type-radio" v-if="query.action === 'add'">
        <el-radio @click.native.prevent="actionChange(item.value)" v-model="purchaseTypeValue"
                  v-for="item in purchaseTypeArray" :key="item.value"
                  :label="item.value">{{item.label}}
        </el-radio>
      </el-row>
      <v-form :formProps="editForm" ref="form"
              v-on:selectOnChange="selectOnChange"
              v-on:handleReset="handleReset"
              v-on:elseBtnHandleReset="elseBtnHandleReset"
              v-on:coverFormData="coverFormData">
      </v-form>
    </div>
    <el-dialog
      title="选择采购计划"
      @open="openDialog"
      :visible.sync="dialogVisible"
      width="90%"
    >
      <div>
        <el-row class="pur-order-dialog-tips">提示:列表为上月1日到月底未处理的采购计划</el-row>
        <v-table :tableParams="purPlanTableParams"
                 v-on:handleOperation="handleDialogOperation"></v-table>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button size="small" @click="dialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <div class="stand">
      <div style="line-height:45px;margin:0 10px">
        <el-row>
          <el-col :span="4">
            <el-button type="primary" @click="emptySelectProduct" size="small">清空采购内容</el-button>
          </el-col>
          <el-col :span="20">
            <div style="float: right">
              <span class="tip-purchase"> 总采购价:&nbsp;<span class="tip-purchase-price">￥{{totalPrice}}</span></span>
              <span class="tip-purchase"> 小计:&nbsp;<span class="tip-purchase-price">￥{{totalArray[0]}}</span></span>
              <span class="tip-purchase"> 总数量:&nbsp;<span class="tip-purchase-price">{{totalArray[1]}}/个</span></span>
              <span class="tip-purchase"> 总额外费用:&nbsp;<span class="tip-purchase-price">￥{{totalArray[2]}}</span></span>
              <span><a style="color:#409EFF;font-size: 12px;cursor: pointer" @click="adjustMoneyOpt">调整采购金额</a></span>
            </div>
          </el-col>
        </el-row>
      </div>
      <div style="margin:0 10px">
        <v-table :tableParams="tableParams"
                 v-on:inputNumChange="inputNumChange"
                 v-on:handleOperation="handleOperation"
                 style="margin-top: 10px">
        </v-table>
      </div>
    </div>
    <el-dialog title="温馨提示" :visible.sync="isAdjustMoney" width="30%" style="margin-top:10%!important;">
      <el-row >
        您本次可调整金额为：<span style="color: red"> ￥{{totalPrice}}</span>
      </el-row>
      <el-form :model="form">
        <el-form-item label="请输入调整金额" style="margin-bottom: 5px;">
          <el-input v-model="form.money"  placeholder="请输入调整金额"></el-input>
        </el-form-item>
        <el-form-item label="请输入备注" >
          <el-input v-model="form.memo"  placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isAdjustMoney = false" size="medium">取 消</el-button>
        <el-button type="primary" @click="sureAdjust" size="medium">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import VTable from "components/common/PageTable/VTable"
  import VForm from "components/common/VForm"
  import VButton from "components/common/VButton"
  import SplitVertical from "components/common/SplitVertical"
  import {localStorage} from 'js/localStorage'

  const purOrderTypeData = {
    '1': '常规订单',
    '2': '集采订单',
    '3': '天猫订单'
  };
  export default {
    components: {
      VForm, VTable, VButton, SplitVertical
    },
    data() {
      return {
        form:{
          money:0,
          memo:'',
        },

        isAdjustMoney:false,
        planId: -1,
        totalPrice:0,
        supplyListData: [],
        purPlanList: [],
        dialogVisible: false,
        purchaseTypeValue: '1',
        adjustMoney: 0,
        purchaseTypeArray: [
          {
            label: '直接创建',
            value: '1'
          }, {
            label: '按照采购计划创建',
            value: '2'
          }
        ],
        title: '创建采购单',
        query: {},
        dataCount: [0, 0, 0],
        totalArray: [0, 0, 0],
        editForm: {
          col: 4,
          labelWidth: '120px',
          elseBtn: {
            show: true,
            text: '返回',
            type: 'default',
            size: 'small',
            style: {},
          },
          formItemArray: [{
            label: '订单类型',
            placeholder: "请选择",
            rules: [{required: true, message: '请选择订单类型', trigger: 'blur'}],
            prop: 'purOrderType',
            itemType: 'select',
            options: [
              {value: '1', label: '常规订单'},
              {value: '2', label: '集采订单'},
              {value: '3', label: '天猫订单'}
            ],
            value: ''
          }, {
            label: '单据日期',
            prop: 'purBillsDate',
            rules: [{required: true, message: '请选择单据日期', trigger: 'change'},],
            placeholder: "选择日期时间",
            itemType: 'dateTime',
            value: ''
          }, {
            label: '预计到货日期',
            prop: 'predictTime',
            placeholder: "选择日期时间",
            itemType: 'dateTime',
            rules: [{required: true, message: '请选择到货日期', trigger: 'change'},],
            value: ''
          }, {
            label: '采购公司',
            placeholder: "请选择",
            rules: [{required: true, message: '请选择采购公司', trigger: 'change'}],
            prop: 'companyId',
            itemType: 'select',
            options: [],
            value: ''
          }, {
            label: '选择仓库',
            placeholder: "请选择",
            prop: 'depotId',
            rules: [{required: true, message: '请选择仓库', trigger: 'change'},],
            itemType: 'select',
            options: [],
            value: ''
          }, {
            label: '供应商',
            placeholder: "请选择",
            prop: 'supplyId',
            rules: [{required: true, message: '请选择供应商', trigger: 'change'},],
            itemType: 'select',
            options: [],
            value: ''
          }, {
            label: '商品名称',
            placeholder: "请选择",
            prop: 'productId',
            // rules: [{required: true, message: '请选择商品名称', trigger: 'change'},],
            itemType: 'select',
            options: [],
            value: ''
          }]
        }, purPlanTableParams: {
          dataArray: [],
          showMultiSelection: false,
          columnArray: [
            {label: '订单类型', prop: 'purOrderType', sortable: false, width: '80'},
            {label: '创建时间', prop: 'createTime', width: '160', sortable: false},
            {label: '订单日期', prop: 'purBillsDate', width: '160', sortable: false},
            {label: '采购公司', prop: 'companyName', sortable: false},
            {label: '仓库', prop: 'depotName', sortable: false, width: "120"},
            {label: '供应商', prop: 'supplyName', sortable: false},
            {label: '采购总金额', prop: 'price', sortable: true, width: "120"},
            {label: '商品总数量', prop: 'total', sortable: true, width: "120"},
            {label: '其他总费用', prop: 'elsePrice', sortable: true, width: "120"},
          ],
          rowHandle: {
            view: {
              show: false
            },
            update: {
              show: false,
            },
            deleted: {
              text: '选择',
            }
          }
        }, tableParams: {
          dataArray: [],
          showMultiSelection: false,
          showOperationColumn: true,
          operationColumnWidth: 100,
          columnArray: [
            {label: '商品名称', prop: 'productName', sortable: false, width: "240", formatType: 'a'},
            {label: '商品品牌', prop: 'brandCode', sortable: false, width: "100"},
            {label: '商品编码', prop: 'productNo', sortable: false, width: "100"},
            {label: '重量', prop: 'productWeight', sortable: false, width: '80',},
            {label: '进货价(含税运)', prop: 'purchasePrice', sortable: false, width: "120"},
            {
              label: '采购单价',
              prop: 'productPrice',
              sortable: false,
              width: "120",
              formatType: 'inputNum',
              step: 0.1,
              max: 999999999999,
              min: 0,
              unShowTip: true
            },
            {
              label: '采购数量',
              prop: 'purNumber',
              sortable: false,
              width: "120",
              formatType: 'inputNum',
              step: 0.1,
              max: 999999999999,
              min: 0,
              unShowTip: true
            },
            {label: '采购金额', prop: 'money', sortable: false, width: "110"},
            {
              label: '其他费用',
              prop: 'elsePrice',
              sortable: false,
              width: "120",
              formatType: 'inputNum',
              step: 0.1,
              max: 999999999999,
              min: 0,
              unShowTip: true
            },
            {label: '备注', prop: 'memo', sortable: false, formatType: 'input', unShowTip: true},
          ],
          rowHandle: {
            deleted: {
              text: '移除',
            },
            update: {
              show: false
            },
            view: {
              show: false
            },
          }
        },
      }
    },

    created() {
      this.userId = localStorage.get('userID')
      this.getSupplyList();
      //获取仓库
      this.getDepotData();
      //调用公司
      this.callCompany();
      //采购计划
      this.getPurPlanList();
      this.query = this.$route.query;

      if (this.query.action !== 'add') {
        this.title = '编辑采购单';
        this.getPurOrderItemList();
      }
    },
    methods: {
      sureAdjust(){
        this.adjustMoney = this.form.money;
        this.isAdjustMoney = false;
      },
      adjustMoneyOpt() {
        this.isAdjustMoney=true
        //
        // this.$prompt('请输入调整金额您当前总采购金额为:' + this.totalPrice, '系统提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   // inputPattern: ,
        //   // inputErrorMessage: '邮箱格式不正确'
        // }).then(({value}) => {
        //   this.adjustMoney = value;
        // }).catch(() => {
        //
        // });
      },
      getPurOrderItemList() {
        let success = data => {
          if (data.code === 'OK') {

            this.tableParams.dataArray = data.data.items;
            // console.log(data.data.entity,"enty")
            this.editForm.formItemArray.forEach(item => {
              for (let key in data.data.entity) {
                if (item.prop === key) {
                  item.value = data.data.entity[key];
                  if (item.prop === 'supplyId') {
                    this.bySupplyGetShop(data.data.entity[key]);
                  }
                }
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        };
        this.api.buyPurListItem({purBillsId: this.query.purBillsId}, success);
      },
      openDialog() {
        this.$nextTick(() => {
          this.purPlanTableParams.dataArray = this.purPlanList;
        });
      },
      actionChange(label) {
        this.purchaseTypeValue = label;
        if (this.purchaseTypeValue === '2') {
          this.dialogVisible = true;
        } else {
          this.planId = -1;
        }
      },
      getPurPlanList() {
        let success = data => {
          if (data.code === 'OK') {
            data.data.forEach(element => {
              element.purBillsDate = this.formatSystemDate(element.purBillsDate);
              element.createTime = this.formatSystemDate(element.createTime);
              element.predictTime = this.formatSystemDate(element.predictTime);
              element.purOrderType = purOrderTypeData[element.purOrderType];
              // element.price = this.currency.numFormat(element.price);
              // element.elsePrice = this.currency.numFormat(element.elsePrice);
            });
            this.purPlanList = data.data;
          } else {
            this.$message.error(data.msg)
          }
        };
        this.api.searchConditionPurPlanBList({userId: this.userId}, success)
      },
      elseBtnHandleReset() {
        let query = {};
        if (this.query.action !== 'add') {
          query = {searchCondition: this.query.searchCondition}
        }
        this.$router.push({
          path: '/my-review',
          query: query
        });
      },
      getPlanProductList(purPlanId) {
        let success = data => {
          if (data.code === 'OK') {
            this.tableParams.dataArray = data.data.items;
            this.editForm.formItemArray.forEach(item => {
              for (let key in data.data.entity) {
                if (item.prop === key) {
                  item.value = data.data.entity[key];
                  if (item.prop === 'supplyId') {
                    this.bySupplyGetShop(data.data.entity[key]);
                  }
                }
              }
            });

          } else {
            this.$message.error(data.msg);
          }
        };
        this.api.purchasePlanItems(purPlanId, success);
      },
      inputNumChange(values) {
        this.dataCount = values.total;
        this.totalPrice = this.currency.numFormat( this.calculate.operation( values.total[0] ,values.total[2],'+'));
        this.totalArray = [this.currency.numFormat(values.total[0]), values.total[1], this.currency.numFormat(values.total[2])];
      },
      emptySelectProduct() {
        if (this.tableParams.dataArray.length > 0) {
          this.tips.ConfirmModal('确认要清空采购商品重新选择吗？', () => {
            this.tableParams.dataArray = [];
            this.totalArray = [0, 0, 0];
            this.editForm.formItemArray.forEach(item => {
              if (item.prop === 'productId') {
                item.value = '';
              }
            });
          });
        }
      },
      empProductSelect() {
        this.editForm.formItemArray.forEach(item => {
          if (item.prop === 'productId') {
            item.options = [];
            item.value = '';
          }
        });
        this.totalArray = [0, 0, 0];
        this.tableParams.dataArray = [];
      },
      handleReset(formName) {
        this.$refs.form.resetForm(formName);
        this.empProductSelect();
      },
      validateSubmitData(productList) {
        if (productList.length < 1) {
          this.tips.MessageModal('warning', '请先选择采购商品！');
          return false;
        }
        let message = '';
        for (let i = 0; i < productList.length; i++) {
          delete productList[i].id;
          if (productList[i].productPrice <= 0) {
            message = '商品【' + productList[i].productName + '】采购价必须大于0';
            break;
          }
          if (productList[i].purNumber < 1) {
            message = '商品【' + productList[i].productName + '】采购数量须大于1';
            break;
          }
        }
        if (message !== '') {
          this.tips.MessageModal('warning', message);
          return false;
        }
        return true;
      },
      coverFormData(valueData) {
        let productList = Object.assign([], this.tableParams.dataArray);
        let result = this.validateSubmitData(productList);
        if (!result) {
          return;
        }
        this.supplyListData.forEach(item => {
          if (item.supplyId === valueData.supplyId) {
            valueData['supplyCode'] = item.supplyCode;
          }
        });
        valueData['total'] = this.dataCount[1];
        valueData['productList'] = productList;
        valueData['adjustMoney'] = this.adjustMoney;
        valueData['memo'] = this.form.memo;
        valueData['price'] = this.dataCount[0];
        valueData['elsePrice'] = this.dataCount[2];
        valueData['state'] = 1;
        if (this.planId !== -1) {
          valueData['purPlanId'] = this.planId;
        }
        if (this.query.action !== 'add') {
          valueData['purBillsId'] = this.query.purBillsId;
          this.edit(valueData);
        } else {
          valueData['userId'] = this.userId;
          this.add(valueData);
        }

      },
      add(valueData) {
        let success = data => {
          if (data.code === 'OK') {
            this.tips.MessageModal('success', '新增成功！');
            this.$router.push({
              path: '/my-review',
            });
          } else {
            this.$message.error(data.msg);
          }
        };
        this.api.buyPurAdd(valueData, success);
      },
      edit(valueData) {
        let success = data => {
          if (data.code === 'OK') {
            this.tips.MessageModal('success', '编辑成功');
            this.$router.push({
              path: '/my-review',
              query: {searchCondition: this.query.searchCondition}
            });
          } else {
            this.$message.error(data.msg);
          }
        };
        this.api.updatePurchaseOrder(valueData, success);
      },
      handleDialogOperation(rowIndex, row) {
        this.planId = row.id;
        this.getPlanProductList(row.id);
        this.dialogVisible = false;
      },
      handleOperation(rowIndex, row) {
        this.tips.ConfirmModal('确认移除商品【' + row.productName + '】吗？', () => {
          this.tableParams.dataArray.splice(rowIndex, 1);
        });
      },
      analysisProduct() {
        let totalPrice = 0;
        let totalElsePrice = 0;
        let totalNum = 0;
        this.tableParams.dataArray.forEach(el => {
          totalPrice += el.money;
          totalElsePrice += el.elsePrice;
          totalNum += el.purNumber;
        });
        this.dataCount = [totalPrice, totalNum, totalElsePrice];
        this.totalPrice = this.currency.numFormat( this.calculate.operation( totalPrice , totalElsePrice,'+'));
        totalPrice = this.currency.numFormat(totalPrice);
        totalElsePrice = this.currency.numFormat(totalElsePrice);
        this.totalArray = [totalPrice, totalNum, totalElsePrice];

      },
      selectOnChange(value, item) {
        if (value === '') {
          return;
        }
        if (item.prop === 'supplyId') {
          this.bySupplyGetShop(value);
          this.empProductSelect();
        } else if (item.prop === "productId") {
          let element = {};
          item.options.forEach(em => {
            if (em.item.id === value) {
              element = em.item;
            }
          });
          let row = {
            id: element.id,
            productItemId: element.productId,
            brandCode: element.brandCode,
            productNo: element.supplyProductNo,
            elsePrice: 0,
            memo: '',
            money: 0,
            productPrice: 0,
            productName: element.productName,
            purNumber: 0,
            productWeight: element.productWeight,
            purchasePrice: element.purchasePrice,
            productUnit: element.productUnit,
          };
          this.tableParams.dataArray.push(row);
          let hash = {};
          this.tableParams.dataArray = this.tableParams.dataArray.reduce(function (pre, next) {
            hash[next.productName] ? '' : hash[next.productName] = true && pre.push(next);
            return pre
          }, []);

        }
      },
      callCompany() {
        let param = {
          pageIndex: 1,
          pageSize: 20,
        };
        let success = data => {
          if (data.code === 'OK') {
            this.editForm.formItemArray.forEach(item => {
              if (item.prop === 'companyId') {
                item.options = this.buildExceptKeyAndValue(data.data, "companyName", "id", "label", "value");
              }
            });
          } else {
            this.$message.error(data.msg)
          }
        };
        this.api.addCompanyList(param, success)
      },
      //通过供应商的id显示商品
      bySupplyGetShop(supplyId) {
        let success = data => {
          if (data.code === "OK") {
            this.editForm.formItemArray.forEach(item => {
              if (item.prop === 'productId') {
                item.options = this.buildExceptKeyAndValue(data.data, "productName", "id", "label", "value");
              }
            });
          } else {
            this.$message.error(data.msg)
          }
        };
        this.api.erpPurSupplyProduct({supplyId: supplyId}, success)
      },
      //获取仓库的select列表
      getDepotData() {
        let param = {
          pageIndex: 1,
          pageSize: 20,
        }
        let success = data => {
          if (data.code === 'OK') {
            this.editForm.formItemArray.forEach(item => {
              if (item.prop === 'depotId') {
                item.options = this.buildExceptKeyAndValue(data.data, "depotName", "id", "label", "value");
              }
            });
          } else {
            this.$message.error(data.msg)
          }
        }
        this.api.depotList(param, success)
      },
      //供应商的接口
      getSupplyList() {
        let success = data => {
          if (data.code === 'OK') {
            this.supplyListData = data.data;
            this.editForm.formItemArray.forEach(item => {
              if (item.prop === 'supplyId') {
                item.options = this.buildExceptKeyAndValue(data.data, "supplyName", "supplyId", "label", "value");
              }
            });
          } else {
            this.$message.error(data.msg)
          }
        }
        this.api.erpPurSupply({}, success)
      }
    }, watch: {
      'tableParams.dataArray': function () {
        this.analysisProduct();
      }
    }
  }
</script>
<style scoped>
  .el-form-item {
    margin-bottom: 13px !important;
  }
</style>
<style lang="scss" scoped>
  .tip-purchase {
    font-size: 12px;
    color: lightslategrey;
    line-height: 32px;
    font-weight: bold;
  }
  .tip-purchase-price {
    font-weight: bold;
    color: red;
    font-size: 18px;
  }

  .purOrder-type-radio {
    padding-left: 40px;
    margin-bottom: 15px;
    margin-top: 10px
  }

  .pur-order-dialog-tips {
    color: goldenrod;
    font-size: 12px;
    padding-left: 10px;
  }
  .editMenu{
    height:200px;background: #fff;padding-right: 10px;
  }
  .addMenu{
    height:245px;background: #fff;padding-right: 10px;
  }
</style>

